package auth

import (
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	logic2 "iot-base/auth/api/logic"
	"iot-base/auth/logger"
	"iot-base/auth/svc"
	types2 "iot-base/auth/types"
	"strings"
)

type GroupInfo struct {
	Id    int64   `json:"id" form:"id"`
	Pid   int64   `json:"pid" form:"pid"`
	Name  string  `json:"group_name" form:"group_name"`
	Rules []int64 `json:"rules" form:"rules"`
}

// FindGroup 查询组.
func FindGroup(c *gin.Context) {
	uid, _ := c.Get("uid")
	resp := types2.NewResult(c)
	logic := logic2.NewGroupLogic()
	ret, err := logic.GetChildrenGroupIds(uid.(int64))
	if err != nil {
		resp.ErrorCode(types2.DBError, err.Error())
		return
	}
	resp.Success(ret)
}

// AddGroup 添加权限组.
func AddGroup(c *gin.Context) {
	requestId, _ := c.Get("RequestId")
	resp := types2.NewResult(c)
	var groupInfo GroupInfo
	err := c.ShouldBind(&groupInfo)
	if err != nil {
		logger.Log.Errorf("[%s] err:=%v", requestId, err)
		resp.ErrorCode(types2.ParamsError, "")
		return
	}
	groupLogic := logic2.NewGroupLogic()
	_, err = groupLogic.AddGroup(groupInfo.Pid, groupInfo.Name)
	if err != nil {
		logger.Log.Errorf("[%s] err:=%v", requestId, err)
		resp.ErrorCode(types2.ExceptionError, err.Error())
	}
	resp.Success(gin.H{})
}

// DelGroup 删除权限组.
func DelGroup(c *gin.Context) {
	requestId, _ := c.Get("RequestId")
	resp := types2.NewResult(c)
	var groupInfo GroupInfo
	err := c.ShouldBind(&groupInfo)
	if err != nil {
		logger.Log.Errorf("[%s] err:=%v", requestId, err)
		resp.ErrorCode(types2.ParamsError, err.Error())
		return
	}
	groupLogic := logic2.NewGroupLogic()
	_, err = groupLogic.DelGroup(groupInfo.Id)
	if err != nil {
		logger.Log.Errorf("[%s] err:=%v", requestId, err)
		if strings.Contains(err.Error(), "user_groups") {
			// 有关联用户
			resp.ErrorCode(types2.DelRelationUser, "")
			return
		}
		resp.ErrorCode(types2.ExceptionError, err.Error())
		return
	}
	// 删除组与设备的关联
	svc.Dao.TAuthGroupStation.DelGroupStation(groupInfo.Id)
	resp.Success(gin.H{})
}

// EditGroup 修改组.
func EditGroup(c *gin.Context) {
	requestId, _ := c.Get("RequestId")
	resp := types2.NewResult(c)
	var groupInfo GroupInfo
	err := c.ShouldBind(&groupInfo)
	if err != nil || groupInfo.Id == 0 {
		logger.Log.Errorf("[%s] err:=%v", requestId, err)
		resp.ErrorCode(types2.ParamsError, err.Error())
		return
	}
	groupLogic := logic2.NewGroupLogic()
	_, err = groupLogic.EditGroup(groupInfo.Id, groupInfo.Pid, groupInfo.Name, groupInfo.Rules)
	if err != nil {
		logger.Log.Errorf("[%s] err:=%v", requestId, err)
		resp.ErrorCode(types2.ExceptionError, err.Error())
		logrus.StandardLogger()
	}
	resp.Success(gin.H{})
}
